package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.util.ExceptionUtil;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.MinioException;
import com.atguigu.tingshu.album.service.FileUploadService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucketName}")
    private String bucketName;
    @Value("${minio.endpointUrl}")
    private String endpointUrl;

    @Override
    public String fileUpload(MultipartFile file) {
        try {
            BufferedImage read = ImageIO.read(file.getInputStream());

            if (read == null) {
                throw new GuiguException(400, "图片格式非法！");
            }
            // 检查存储桶是否存在，不存在则创建
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }

            // 生成唯一的对象名称
            String s = FileUtil.extName(file.getOriginalFilename());
            String objectName = IdUtil.fastSimpleUUID() + "." + s;
            //文件夹
            String folder = "/" + DateUtil.today() + "/";
            String name = folder + objectName;
            // 上传图片
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(name)
                            .stream(file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());

            // 生成文件访问 URL
            String objectUrl = endpointUrl + "/" + bucketName + name;
            System.out.println(objectUrl);

            return objectUrl;
        } catch (Exception e) {
            log.error("[专辑服务]上传图片文件异常：{}", e);
            throw new RuntimeException();
        }
    }
}